<!-- <route lang="yaml">
  meta:
    enabled: false
  </route> -->

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { GetDataDetail, PostAddCoupon, PutCouponModify } from '@/api/modules/voucher.ts'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref({
  name: '',
  price: 0,
  type: undefined,
  count: undefined,
  productCode: '',
  flag: 0,
  // validDays: undefined,
  picUrl: '',
  intro: '',
  // startTime: '',
  endTime: '',
  relateProduct: 0,
  relateProductBanner: '',
  type3PriceArray: [],
})
const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入券面值', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  count: [
    { required: true, message: '请输入数量', trigger: 'blur' },
  ],
  productCode: [
    { required: true, message: '请输入编码', trigger: 'blur' },
  ],
  // validDays: [
  //   { required: true, message: '请输入有效天数', trigger: 'blur' },
  // ],
  picUrl: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  intro: [
    { required: true, message: '请输入分享描述', trigger: 'blur' },
  ],
  // startTime: [
  //   { required: true, message: '请选择生效时间', trigger: 'blur' },
  // ],
  endTime: [
    { required: true, message: '请选择失效时间', trigger: 'blur' },
  ],
})

const typeArr = [
  {
    value: 1,
    label: '赠品券',
  },
  {
    value: 2,
    label: '奖品券',
  },
  {
    value: 3,
    label: '满减券',
  },
]

function handleUploadSuccess(key: string, urls: string) {
  // console.log(urls)
  if (urls) {
    ruleForm.value[key] = urls
  }
}

const id = route.query.id as string

function checkDuplicateSalePrice() {
  const salePrices = ruleForm.value.type3PriceArray.map((item: any) => item.sale_price)
  const uniqueSalePrices = new Set(salePrices)

  if (salePrices.length !== uniqueSalePrices.size) {
    return false
  }

  return true
}
// 添加
async function AddData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      if (ruleForm.value.type === 3 ? checkDuplicateSalePrice() : true) {
        PostAddCoupon(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyVoucher()
            router.push({
              name: 'voucherIndex',
            })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
      else {
        ElMessage.error('满减不能相同，请修改满减的要求')
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}
// 编辑
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      if (ruleForm.value.type === 3 ? checkDuplicateSalePrice() : true) {
        // ruleForm.value.relateProductBanner = '/upload/zrgreq202503281626014876.jpg'
        PutCouponModify(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({
              name: 'voucherIndex',
            })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        ElMessage.error('满减不能相同，请修改满减的要求')
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

function SetPrice() {
  if (ruleForm.value.type === 3) {
    if (!ruleForm.value.type3PriceArray) {
      ruleForm.value.type3PriceArray = []
    }
    if (ruleForm.value.type3PriceArray?.length !== 3) {
      ruleForm.value.type3PriceArray?.push({
        price: 0,
        sale_price: 0,
      })
    }
    else {
      ElMessage.error('最多添加三个')
    }
  }
}
function DeleteCarousel(index: number) {
  ruleForm.value.type3PriceArray.splice(index, 1)
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberVoucher(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetVoucherData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="类型" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择">
                <el-option v-for="item in typeArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="数量" prop="count">
              <el-input v-model="ruleForm.count" placeholder="请输入数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="编码" :prop="ruleForm.type !== 3 ? 'productCode' : ''">
              <el-input
                v-model.trim="ruleForm.productCode" placeholder="请输入编码"
                :parser="(value: any) => {
                  value.replace(/[\s\t]/g, '');
                }"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.type !== 3" :md="8">
            <ElFormItem label="券面值" prop="price">
              <el-input v-model="ruleForm.price" placeholder="请输入券面值" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="是否能关联商品" prop="relateProduct">
              <el-radio-group v-model="ruleForm.relateProduct">
                <el-radio :value="1">
                  是
                </el-radio>
                <el-radio :value="0">
                  否
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享描述" prop="intro">
              <el-input v-model="ruleForm.intro" placeholder="请输入分享描述" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="失效时间" prop="endTime">
              <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择失效日期和时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="max-width: 300px;"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="状态" prop="flag">
              <el-switch
                v-model="ruleForm.flag"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="停用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.type === 3" :md="24">
            <ElFormItem label="满减券配置" prop="type3PriceArray">
              <div class="mb-5 w-full">
                <el-button type="success" @click="SetPrice">
                  新增
                </el-button>
              </div>
              <ElCol v-for="(item, index) in ruleForm.type3PriceArray" :key="item.id" :md="6" class="mb-5">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>配置</span>
                    </div>
                  </template>
                  满 <el-input v-model="item.sale_price" style="max-width: 100px;" /> 减 <el-input v-model="item.price" style="max-width: 100px;" />
                  <template #footer>
                    <div class="text-right">
                      <el-button type="danger" @click="DeleteCarousel(index)">
                        删除
                      </el-button>
                    </div>
                  </template>
                </el-card>
              </ElCol>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传封面">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="列表封面" prop="picUrl">
              <ImageUpload
                :ext="['jpg', 'png']" :size="5" width="150" height="auto"
                :url="ruleForm.picUrl" @on-success="(url) => handleUploadSuccess('picUrl', url)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.relateProduct === 1" :md="16">
            <ElFormItem label="关联商品Banner">
              <ImageUpload
                :ext="['jpg', 'png']" :size="5" width="auto" height="150"
                :url="ruleForm.relateProductBanner" @on-success="(url) => handleUploadSuccess('relateProductBanner', url)"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton v-if="id" type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
      <ElButton v-else type="primary" size="large" @click="AddData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

  <style lang="scss" scoped>
  :deep(.el-date-editor) {
    width: 100%;
  }

  .tag {
    max-width: 300px;
    color: red;
  }
  </style>
